<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :pagination="pagination"
      :rule-form="ruleForms"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @resetForm="resetForm"

    >
    </x-Table>

    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="45%"
    >
      <form-create
        v-model="fapi"
        :rule="rule"
        :option="option"
        :value.sync="formParam"
        @submit="onSubmit"
      >
        <!--        管理员分页-->
        <template slot="type-page-select-paper">
          <el-select @clear="paperClear" :remote-method="paperFilterMethod" remote filterable
                     v-model="rule[1].value"
                     clearable placeholder="请选择">
            <el-option
              style='width: 260px;text-align: center'
              v-for="item in rule[1]['options']"
              :key="item.value"
              :label="item.value + ' => ' + item.label "
              :value="item.value">
            </el-option>
            <el-pagination
              @current-change="paperCurrentChange"
              small
              layout="prev, pager, next"
              :page-size="20"
              :current-page="pageSizes.paperPage.currentPage"
              :total="pageSizes.paperPage.total">
            </el-pagination>
          </el-select>
        </template>
        <!--        end-->
      </form-create>
    </el-dialog>
    <!--    end-->


    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      title="选择学生"
      :visible.sync="userVisible"
      :close-on-click-modal="false"
      width="65%"
    >
      <userList v-if="userVisible" ref="userList" @handleSelectionChange="handleSelectionChange"/>
      <div style="display:flex;justify-content: center">
        <el-button @click="selectUserids" type="primary">确定</el-button>
        <el-button @click="closeUser" type="info">清空/关闭</el-button>
      </div>
    </el-dialog>
    <!--    end-->

  </div>
</template>

<script>
import userList from "./components/userList";

let _this;
export default {
  components: {userList},
  data() {
    return {
      userListIds: [],//用户列表
      userVisible: false,
      pageSizes: {
        paperPage: {
          currentPage: 1,
          total: 0,
        },
      },
      searchParams: {},//搜索对象
      loading: true,
      row: null, //当前选择数据
      ruleForms: {},
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      otherParam: {
        halfCheckedKeys: [],
      }, //如果有其他情况会拼接这个参数
      fapi: {},
      formParam: {},
      rule: [
        {
          "type": "select",
          "field": "admin_id",
          "title": "管理员",
          "info": "",
          effect: {
            fetch: {
              action:
                "http://www.free.com/adminapi/v1.setting.admin.SystemAdmin/searchAccount",
              to: "options",
              method: "POST",
              parse(res) {
                return res.data.data.map((row) => {
                  return {
                    label: row.account,
                    value: row.id,
                  };
                });
              },
            },
          },
          "options": [],
          "_fc_drag_tag": "select",
          "hidden": false,
          "display": true
        },
        {
          "type": "pageSelectPaper",
          "field": "exam_id",
          "title": "考试批次",
          "info": "",
          "options": [],
          "_fc_drag_tag": "select",
          "hidden": false,
          "display": true
        },
        {
          "type": "FcRow",
          "children": [
            {
              "type": "col",
              "props": {
                "span": 12
              },
              "children": [
                {
                  "type": "input",
                  "field": "name",
                  "title": "角色名称",
                  "info": "",
                  "_fc_drag_tag": "input",
                  "hidden": false,
                  "display": true,
                  "validate": [
                    {
                      "trigger": "submit",
                      "mode": "required",
                      "message": "请输入角色名称",
                      "required": true,
                      "type": "string"
                    }
                  ]
                }
              ],
              "_fc_drag_tag": "col",
              "hidden": false,
              "display": true
            }
          ],
          "_fc_drag_tag": "row",
          "hidden": false,
          "display": true
        },
        {
          "type": "FcRow",
          "children": [
            {
              "type": "col",
              "props": {
                "span": 12,
                "offset": 0
              },
              "children": [
                {
                  "type": "input",
                  "field": "user_ids",
                  "title": "监考学生",
                  nativeEmit: ['click'],
                  "props": {
                    "readonly": true
                  },
                  "info": "",
                  "_fc_drag_tag": "input",
                  "hidden": false,
                  "display": true
                }
              ],
              "_fc_drag_tag": "col",
              "hidden": false,
              "display": true
            }
          ],
          "_fc_drag_tag": "row",
          "hidden": false,
          "display": true
        }
      ],
      option: {
        form: {
          inline: false,
          labelPosition: "right",
          size: "small",
          labelWidth: "125px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: false,
        },
        resetBtn: true,
      },
      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      options: {
        fields: {
          id: {label: "ID", prop: "id", width: "80", order: true},
          name: {label: "角色名称", prop: "name", },
          admin_id: {label: "账户名称", prop: "admin_id"},
          exam_id: {label: "考试批次", prop: "exam_id"},
          user_ids: {label: "监考学生", prop: "user_ids"},
          create_time: {label: "创建时间", prop: "create_time"},
          button: {
            label: "操作",
            width: "130",
            type: "func",
            fixed: true,
            edit: function (scope) {
              setTimeout(() => {
                _this.fapi.setValue("admin_id", scope["row"].admin_id);
                _this.fapi.setValue("exam_id", scope["row"].exam_id);
                _this.fapi.setValue("user_ids", scope["row"].user_ids);
                _this.fapi.setValue("name", scope["row"].name);
              }, 0);
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.dialogVisible = true;
            },
            del: function (scope) {
              _this.deleteDate(scope["row"].id);
            },
          },
        },
      },
    };
  },
  methods: {
    closeUser: function () {
      _this.userListIds = [];
      _this.$refs.userList.clearSelection();
      _this.fapi.setValue('user_ids', '')
      _this.userVisible = false;
    },
    selectUserids: function () {
      let data = [];
      if (_this.userListIds.length > 0) {
        _this.userListIds.forEach(item => {
          console.log(item)
          data.push(item.id)
        })
      }
      _this.userListIds = data;
      _this.fapi.setValue('user_ids', data.join());
      _this.userVisible = false;
    },

    handleSelectionChange: function (val) {
      _this.userListIds = val;
    },

    clickUser: function () {

      let obj = _this.fapi.getValue('user_ids');
      if (obj) {
        let data = obj.split(',');
        setTimeout(()=>{
          _this.$refs.userList.clearSelection();
          _this.$refs.userList.handleCurrentChange(data);
        },0)
      }
      _this.userVisible = true;
    },

    paperClear: function () {
      _this.getPaperList();
    },
    paperFilterMethod: function (val) {
      _this.getPaperList(1, val);
    },
    paperCurrentChange: function (val) {
      _this.getPaperList(val)
    },

    getPaperList: function (page = 1, val) {
      _this.$store
        .dispatch("exam/getExamSendList", {
          title: val,
          page: page,
        })
        .then(() => {
          _this.rule[1].options = [];
          let data = this.$store.state.exam.examSendList;
          if (data) {
            data.data.forEach((item) => {
              let obj = {
                label: item.title,
                value: item.id
              }
              _this.rule[1].options.push(obj);
            })
          }
          _this.pageSizes["paperPage"]['currentPage'] = data["current_page"];
          _this.pageSizes["paperPage"]['total'] = data["current_page"];
        });
    },

    handlePaginationCurrentChange: function (val) {
      _this.loading = true;
      _this.pagination["currentPage"] = val;
      _this.getDateList(_this.searchParams);
    },

    handlePaginationSizeChange: function (val) {
      _this.loading = true;
      _this.pagination["pageSize"] = val;
      _this.getDateList(_this.searchParams);
    },

    /**
     * 获取所有数据
     */
    getDateList: function () {
      _this.$store
        .dispatch("exam/getExamMonitorList", {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          let data = this.$store.state.exam.examMonitorList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },


    /**
     * 批量删除
     */
    handleHeardDel: function (val) {
      let del = [];
      val.forEach((item, index) => {
        del.push(item.id);
      });
      _this.deleteDate(del);
    },


    createMonitorOrUpdate: function (param) {
      _this.$store
        .dispatch("exam/createMonitorOrUpdate", {
          id: _this.row == null ? '' : _this.row.id,
          name:param['name'],
          admin_id: param["admin_id"],
          exam_id: param["exam_id"],
          user_ids: param["user_ids"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.$message.success(msg);
            _this.getDateList();
          } else {
            _this.$message.error(msg);
          }
        });
    },
    /**
     * 表单提交回调
     */
    onSubmit: function (val) {
      _this.createMonitorOrUpdate(val);
    },

    resetForm: function () {
      _this.searchParams = {};
    },

    /**
     * 搜索角色标题
     */
    searchForm: function (val) {
      // _this.searchParams = val;
      // _this.loading = true;
      // _this.getDateList(val);
    },
    search(val) {
      _this.$store
        .dispatch("office/searchStudent", {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
          name: val.name,
          sex: val.sex,
          idcard: val.idcard,
          phone: val.phone,
          student_number: val.student_number,
          exam_number: val.exam_number,
          enter_batch: val.enter_batch,
          enter_type: val.enter_type,
        })
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          let data = this.$store.state.office.studentList;
          if (data) {
            this.tableData = data.data;
            _this.pagination["currentPage"] = data["current_page"];
            _this.pagination["total"] = data["total"];
          }
        });
    },


    /**
     * 删除角色
     */
    deleteDate: function (val) {
      _this.loading = true;
      _this.$store
        .dispatch("exam/delMonitorList", {
          id: val,
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     *  表单导航栏添加点击
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      _this.row = null;
      this.dialogVisible = true;
    },
  },
  watch: {
    dialogVisible(newVal) {
      setTimeout(() => {
        _this.fapi.on('native-user_ids-click', this.clickUser)
        if (!newVal) {
          _this.fapi.resetFields(); //清空数据
        }
      }, 0);
    },
    userVisible(newVal){
      if (!newVal){
        _this.$refs.userList.clearSelection();
      }
    }

  },
  created() {
    _this = this;
  },
  mounted() {
    this.getDateList();
    this.getPaperList();
  },
};
</script>

<style scoped></style>


